package api

import (
	"context"
	"fmt"
	"gateway/basic/config"
	user "gateway/basic/proto/userproto"
	"gateway/handler/request"
	"gateway/handler/response"
	"github.com/gin-gonic/gin"
	"log"
)

// UserDetail
// @Summary      用户详情
// @Description  用户详情
// @Tags         用户模块
// @Accept       json
// @Produce      json
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /user/userDetail [get]
func UserDetail(c *gin.Context) {
	userId := c.GetUint("userId")
	res, err := config.UserClient.UserDetail(c, &user.UserDetailReq{Id: uint64(userId)})
	if err != nil {
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "查询成功", res)
}

// RealUser
// @Summary      实名认证
// @Description  实名认证
// @Tags         用户模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.RealUserReq  true  "用户参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /user/realUser [post]
func RealUser(c *gin.Context) {
	var req request.RealUserReq
	if err := c.ShouldBind(&req); err != nil {
		response.SrvError(c, "参数格式错误", err.Error())
		return
	}
	userId := c.GetUint("userId")
	fmt.Println(userId)
	_, err := config.UserClient.RealName(c, &user.RealNameReq{
		Id:       uint64(userId),
		RealName: req.RealName,
		IdCard:   req.IdCard,
	})
	if err != nil {
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "实名成功", nil)
}

// ListInterests
// @Summary      兴趣列表
// @Description  兴趣列表
// @Tags         用户模块
// @Accept       json
// @Produce      json
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /user/listInterests [get]
func ListInterests(c *gin.Context) {
	res, err := config.UserClient.ListInterests(c, &user.ListInterestsReq{})
	if err != nil {
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "查询成功", res)
}

// SetUserInterests
// @Summary      设置兴趣
// @Description  设置兴趣
// @Tags         用户模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.SetUserInterestsReq  true  "用户参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /user/setInterests [post]
func SetUserInterests(c *gin.Context) {
	userId := c.GetUint64("userId")
	var req request.SetUserInterestsReq
	if err := c.ShouldBind(&req); err != nil {
		response.SrvError(c, "参数格式错误", err.Error())
		return
	}
	if len(req.InterestIds) > 10 {
		req.InterestIds = req.InterestIds[:10]
	}
	_, err := config.UserClient.SetUserInterests(c, &user.SetUserInterestsReq{UserId: userId, InterestIds: req.InterestIds})
	if err != nil {
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "保存成功", nil)
}

// GetUserInterests
// @Summary      获取用户兴趣
// @Description  获取用户兴趣
// @Tags         用户模块
// @Accept       json
// @Produce      json
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /user/getInterests [get]
func GetUserInterests(c *gin.Context) {
	userId := c.GetUint64("userId")
	res, err := config.UserClient.GetUserInterests(c, &user.GetUserInterestsReq{UserId: userId})
	if err != nil {
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "查询成功", res)
}

// NewGame
// @Summary      新建游戏
// @Description  新建游戏
// @Tags         用户模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.NewGame  true  "用户参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /user/newGame [post]
func NewGame(c *gin.Context) {
	var req request.NewGame
	if err := c.ShouldBind(&req); err != nil {
		response.SrvError(c, "参数格式错误", err.Error())
		return
	}

	game, err := config.UserClient.NewGame(context.Background(), &user.NewGameRequest{})
	if err != nil {
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "新建游戏成功", game)

}

// Guess
// @Summary      猜测数字
// @Description  猜测数字
// @Tags         用户模块
// @Accept       json
// @Produce      json
// @Param        user  body      request.Guess  true  "用户参数"
// @Success      200  {object}  response.Response
// @Failure      400   {object}  response.Response
// @Failure      500  {object}  response.Response
// @Router       /user/guess [post]
func Guess(c *gin.Context) {
	var req request.Guess
	if err := c.ShouldBind(&req); err != nil {
		response.SrvError(c, "参数格式错误", err.Error())
		return
	}

	guess, err := config.UserClient.Guess(context.Background(), &user.GuessRequest{
		GameId: req.GameId,
		Number: req.Number,
	})
	if err != nil {
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "猜测成功", guess)
}

// GetSoulQuestionCategories 获取灵魂测试题目分类
// @Summary 获取灵魂测试分类
// @Tags 灵魂匹配
// @Success 200 {object} response.Response
// @Router /user/soul/categories [get]
func GetSoulQuestionCategories(c *gin.Context) {
	res, err := config.UserClient.GetSoulQuestionCategories(c, &user.GetSoulQuestionCategoriesReq{})
	if err != nil {
		log.Printf("Error in GetSoulQuestionCategories: error=%v", err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "查询成功", res)
}

// GetSoulQuestions 获取灵魂测试题目
// @Summary 获取灵魂测试题目
// @Tags 灵魂匹配
// @Param category_id query int false "分类ID"
// @Param limit query int false "返回条数"
// @Success 200 {object} response.Response
// @Router /user/soul/questions [get]
func GetSoulQuestions(c *gin.Context) {
	var req request.GetSoulQuestionsReq
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParameterError(c, "参数格式错误: "+err.Error(), nil)
		return
	}
	// 设置默认限制和最大限制
	if req.Limit <= 0 {
		req.Limit = 20
	}
	if req.Limit > 100 {
		req.Limit = 100
	}

	res, err := config.UserClient.GetSoulQuestions(c, &user.GetSoulQuestionsReq{
		CategoryId: req.CategoryId,
		Limit:      req.Limit,
	})
	if err != nil {
		log.Printf("Error in GetSoulQuestions: categoryId=%d, limit=%d, error=%v", req.CategoryId, req.Limit, err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "查询成功", res)
}

// SubmitSoulAnswer 提交灵魂测试答案
// @Summary 提交灵魂测试答案
// @Tags 灵魂匹配
// @Param req body request.SubmitSoulAnswerReq true "答案"
// @Success 200 {object} response.Response
// @Router /user/soul/answer [post]
func SubmitSoulAnswer(c *gin.Context) {
	userId := c.GetUint64("userId")
	if userId == 0 {
		response.ParameterError(c, "用户未登录", nil)
		return
	}
	var req request.SubmitSoulAnswerReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数格式错误: "+err.Error(), nil)
		return
	}

	// 验证答案分数范围
	if req.AnswerScore < 0 || req.AnswerScore > 100 {
		response.ParameterError(c, "答案分数必须在0-100之间", nil)
		return
	}

	res, err := config.UserClient.SubmitSoulAnswer(c, &user.SubmitSoulAnswerReq{
		UserId:        userId,
		QuestionId:    req.QuestionId,
		AnswerContent: req.AnswerContent,
		AnswerScore:   req.AnswerScore,
	})
	if err != nil {
		log.Printf("Error in SubmitSoulAnswer: userId=%d, questionId=%d, error=%v", userId, req.QuestionId, err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, res.Message, res)
}

// CompleteSoulTest 完成灵魂测试
// @Summary 完成灵魂测试
// @Tags 灵魂匹配
// @Param req body request.CompleteSoulTestReq true "测试版本/时长"
// @Success 200 {object} response.Response
// @Router /user/soul/complete [post]
func CompleteSoulTest(c *gin.Context) {
	userId := c.GetUint64("userId")
	if userId == 0 {
		response.ParameterError(c, "用户未登录", nil)
		return
	}
	var req request.CompleteSoulTestReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数格式错误: "+err.Error(), nil)
		return
	}

	// 验证测试时长范围（1秒到1小时）
	if req.TestDuration < 1 || req.TestDuration > 3600 {
		response.ParameterError(c, "测试时长必须在1-3600秒之间", nil)
		return
	}

	res, err := config.UserClient.CompleteSoulTest(c, &user.CompleteSoulTestReq{
		UserId:       userId,
		TestVersion:  req.TestVersion,
		TestDuration: req.TestDuration,
	})
	if err != nil {
		log.Printf("Error in CompleteSoulTest: userId=%d, error=%v", userId, err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, res.Message, res)
}

// GetSoulTestResult 获取灵魂测试结果
// @Summary 获取灵魂测试结果
// @Tags 灵魂匹配
// @Success 200 {object} response.Response
// @Router /user/soul/result [get]
func GetSoulTestResult(c *gin.Context) {
	userId := c.GetUint64("userId")
	if userId == 0 {
		response.ParameterError(c, "用户未登录", nil)
		return
	}

	res, err := config.UserClient.GetSoulTestResult(c, &user.GetSoulTestResultReq{
		UserId: userId,
	})
	if err != nil {
		log.Printf("Error in GetSoulTestResult: userId=%d, error=%v", userId, err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "查询成功", res)
}

// GetSoulMatchCandidates 获取灵魂匹配候选用户
// @Summary 获取灵魂匹配候选用户
// @Tags 灵魂匹配
// @Param limit query int false "返回条数"
// @Success 200 {object} response.Response
// @Router /user/soul/match/candidates [get]
func GetSoulMatchCandidates(c *gin.Context) {
	userId := c.GetUint64("userId")
	if userId == 0 {
		response.ParameterError(c, "用户未登录", nil)
		return
	}
	var req3 request.GetSoulMatchCandidatesReq
	if err := c.ShouldBindQuery(&req3); err != nil {
		response.ParameterError(c, "参数格式错误: "+err.Error(), nil)
		return
	}
	// 设置默认限制和最大限制
	if req3.Limit <= 0 {
		req3.Limit = 10
	}
	if req3.Limit > 50 {
		req3.Limit = 50
	}
	res, err := config.UserClient.GetSoulMatchCandidates(c, &user.GetSoulMatchCandidatesReq{
		UserId: userId,
		Limit:  req3.Limit,
	})
	if err != nil {
		log.Printf("Error in GetSoulMatchCandidates: userId=%d, error=%v", userId, err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "查询成功", res)
}

// GetSoulMatches 获取灵魂匹配列表
// @Summary 获取灵魂匹配列表
// @Tags 灵魂匹配
// @Param limit query int false "返回条数"
// @Success 200 {object} response.Response
// @Router /user/soul/matches [get]
func GetSoulMatches(c *gin.Context) {
	userId := c.GetUint64("userId")
	if userId == 0 {
		response.ParameterError(c, "用户未登录", nil)
		return
	}
	var req request.GetSoulMatchesReq
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParameterError(c, "参数格式错误: "+err.Error(), nil)
		return
	}
	// 设置默认限制和最大限制
	if req.Limit <= 0 {
		req.Limit = 20
	}
	if req.Limit > 100 {
		req.Limit = 100
	}

	res, err := config.UserClient.GetSoulMatches(c, &user.GetSoulMatchesReq{
		UserId: userId,
		Limit:  req.Limit,
	})
	if err != nil {
		log.Printf("Error in GetSoulMatches: userId=%d, error=%v", userId, err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "查询成功", res)
}
